<template>
  <div class="step-panel">
    <h2>{{ stepTitle }}</h2>
    
    <!-- 上部分：入住设置 -->
    <div class="admission-config-section">
      <h3>入住设置</h3>
      <div class="form-grid">
        <!-- 入住期限 -->
        <div class="form-group">
          <label>入住期限 <span class="required">*</span></label>
          <div class="duration-group">
            <input
              type="number"
              v-model="localFormData.admissionConfig.duration"
              min="1"
              placeholder="请输入月数"
              class="duration-input"
            />
            <span class="duration-unit">个月</span>
          </div>
        </div>

        <!-- 护理等级 -->
        <div class="form-group">
          <label>护理等级 <span class="required">*</span></label>
          <el-select
            v-model="localFormData.admissionConfig.levelId"
            placeholder="请选择护理等级"
            clearable
            style="width: 100%"
            v-loading="levelLoading"
            @change="handleLevelChange"
          >
            <el-option
              v-for="level in levelList"
              :key="level.id"
              :label="level.levelName"
              :value="parseInt(level.id)"
            >
              <span style="float: left">{{ level.levelName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ level.nursingFee ? formatPrice(level.nursingFee) + '元/月' : '未设置价格' }}
              </span>
            </el-option>
          </el-select>
        </div>

        <!-- 入住床位 -->
        <div class="form-group">
          <label>入住床位 <span class="required">*</span></label>
          <div class="bed-selection">
            <button 
              type="button" 
              class="bed-select-btn"
              @click="showBedSelection = true"
            >
              {{ localFormData.admissionConfig.selectedBed ? localFormData.admissionConfig.selectedBed.name : '选择床位' }}
            </button>
            <div v-if="localFormData.admissionConfig.selectedBed" class="bed-info">
              <span class="bed-name">{{ localFormData.admissionConfig.selectedBed.name }}</span>
              <span class="bed-type">{{ localFormData.admissionConfig.selectedBed.type }}</span>
              <span class="bed-price">{{ formatPrice(localFormData.admissionConfig.selectedBed.price) }}元/月</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 下部分：费用设置 -->
    <div class="fee-config-section">
      <h3>费用设置</h3>
      
      <!-- 费用提醒 -->
      <div class="fee-notice">
        <div class="notice-icon">💡</div>
        <div class="notice-content">
          <strong>费用说明：</strong>该费用为月账单，每月一号收取当月费用。请根据实际入住时间设置费用期限。
        </div>
      </div>

      <div class="form-grid">
        <!-- 费用期限 -->
        <div class="form-group">
          <label>开始时间 <span class="required">*</span></label>
          <el-date-picker
            v-model="localFormData.feeConfig.startDate"
            type="date"
            placeholder="选择开始日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </div>
        <div class="form-group">
          <label>结束时间 <span class="required">*</span></label>
          <el-date-picker
            v-model="localFormData.feeConfig.endDate"
            type="date"
            placeholder="选择结束日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </div>

        <!-- 押金 -->
        <div class="form-group">
          <label>押金（元）</label>
          <input
            type="number"
            v-model="localFormData.feeConfig.deposit"
            min="0"
            step="0.01"
            placeholder="请输入押金金额"
            @input="handleDepositInput"
          />
        </div>

        <!-- 护理费用 -->
        <div class="form-group">
          <label>护理费用（元/月） <span class="required">*</span></label>
          <input
            type="number"
            v-model="localFormData.feeConfig.careFee"
            min="0"
            step="0.01"
            placeholder="请输入护理费用"
            @input="handleCareFeeInput"
          />
        </div>

        <!-- 床位费用 -->
        <div class="form-group">
          <label>床位费用（元/月） <span class="required">*</span></label>
          <input
            type="number"
            v-model="localFormData.feeConfig.bedFee"
            min="0"
            step="0.01"
            placeholder="请输入床位费用"
            @input="handleBedFeeInput"
          />
        </div>

        <!-- 其他费用 -->
        <div class="form-group">
          <label>其他费用（元/月）</label>
          <input
            type="number"
            v-model="localFormData.feeConfig.otherFee"
            min="0"
            step="0.01"
            placeholder="请输入其他费用"
            @input="handleOtherFeeInput"
          />
        </div>

        <!-- 医保支付 -->
        <div class="form-group">
          <label>医保支付（元/月）</label>
          <input
            type="number"
            v-model="localFormData.feeConfig.medicalInsurance"
            min="0"
            step="0.01"
            placeholder="请输入医保支付金额"
            @input="handleMedicalInsuranceInput"
          />
        </div>

        <!-- 政府补贴 -->
        <div class="form-group">
          <label>政府补贴（元/月）</label>
          <input
            type="number"
            v-model="localFormData.feeConfig.governmentSubsidy"
            min="0"
            step="0.01"
            placeholder="请输入政府补贴金额"
            @input="handleGovernmentSubsidyInput"
          />
        </div>
      </div>

      <!-- 账单预览按钮 -->
      <div class="bill-preview-section">
        <button class="bill-preview-btn" @click="showBillPreview">
          📊 账单预览
        </button>
      </div>
    </div>

    <!-- 床位选择对话框 -->
    <div v-if="showBedSelection" class="dialog-overlay">
      <div class="bed-selection-dialog">
        <h3>选择床位</h3>
        <div class="dialog-content">
          <div class="bed-filter">
            <el-input
              v-model="bedSearchKey"
              placeholder="搜索床位编号或类型"
              clearable
              style="width: 200px; margin-right: 10px;"
            />
            <el-select
              v-model="bedFilterType"
              placeholder="床位类型"
              clearable
              style="width: 120px;"
            >
              <el-option label="单人间" value="单人间"></el-option>
              <el-option label="两人间" value="两人间"></el-option>
              <el-option label="三人间" value="三人间"></el-option>
              <el-option label="四人间" value="四人间"></el-option>
            </el-select>
          </div>
          
        <div class="bed-list" v-loading="bedLoading">
          <div
            v-for="bed in filteredBeds"
            :key="bed.id"
            class="bed-item"
            :class="{ 'bed-selected': localFormData.admissionConfig.selectedBed?.id === bed.id }"
            @click="selectBed(bed)"
          >
            <div class="bed-header">
              <span class="bed-name">{{ bed.bedNo }}</span>
              <span class="bed-status" :class="`status-${bed.status}`">
                {{ (bed.status === 0 || bed.status === '0') ? '空闲' : '已占用' }}
              </span>
            </div>
            <div class="bed-details">
              <span class="bed-type">{{ getBedTypeLabel(bed.bedType) }}</span>
              <span class="bed-price">{{ formatPrice(getBedTypePrice(bed.bedType)) }}元/月</span>
            </div>
            <div class="bed-location">
              <div class="location-row">
                <span class="bed-room">{{ bed.roomName || '未知房间' }}</span>
                <span class="bed-floor">{{ bed.floorName || '' }}</span>
              </div>
              <div class="room-type-info" v-if="bed.roomType">
                <span class="room-type">{{ bed.roomType }}</span>
              </div>
            </div>
          </div>
        </div>
          
          <div v-if="filteredBeds.length === 0" class="no-beds">
            <div>暂无符合条件的床位</div>
            <div style="margin-top: 10px; font-size: 12px; color: #666;">
              调试信息：原始数据 {{ availableBeds.length }} 条，筛选后 {{ filteredBeds.length }} 条
            </div>
            <div style="margin-top: 5px; font-size: 12px; color: #666;">
              当前筛选条件：类型={{ bedFilterType }}，搜索={{ bedSearchKey }}
            </div>
            <div style="margin-top: 5px; font-size: 12px; color: #666;">
              床位类型示例：{{ availableBeds.slice(0, 3).map(bed => `${bed.bedNo}:${bed.bedType}`).join(', ') }}
            </div>
          </div>
        </div>
        <div class="dialog-actions">
          <button class="cancel-btn" @click="showBedSelection = false">取消</button>
          <button class="confirm-btn" @click="confirmBedSelection">确认选择</button>
        </div>
      </div>
    </div>

    <!-- 账单预览对话框 -->
    <div v-if="showBillPreviewDialog" class="dialog-overlay">
      <div class="bill-preview-dialog">
        <h3>费用账单预览</h3>
        <div class="dialog-content">
          <div class="bill-summary">
            <div class="bill-period">
              <strong>费用期限：</strong>
              {{ localFormData.feeConfig.startDate }} 至 {{ localFormData.feeConfig.endDate }}
              （共 {{ calculateMonths }} 个月）
            </div>
            
            <div class="bill-details">
              <h4>费用明细（月）</h4>
              <div class="bill-items">
                <!-- 收入项 -->
                <div class="bill-item income">
                  <span class="item-name">护理费用：</span>
                  <span class="item-amount">+{{ formatPrice(localFormData.feeConfig.careFee) }}元</span>
                </div>
                <div class="bill-item income">
                  <span class="item-name">床位费用：</span>
                  <span class="item-amount">+{{ formatPrice(localFormData.feeConfig.bedFee) }}元</span>
                </div>
                <div class="bill-item income" v-if="localFormData.feeConfig.otherFee > 0">
                  <span class="item-name">其他费用：</span>
                  <span class="item-amount">+{{ formatPrice(localFormData.feeConfig.otherFee) }}元</span>
                </div>
                
                <!-- 支出项 -->
                <div class="bill-item expense" v-if="localFormData.feeConfig.medicalInsurance > 0">
                  <span class="item-name">医保支付：</span>
                  <span class="item-amount">-{{ formatPrice(localFormData.feeConfig.medicalInsurance) }}元</span>
                </div>
                <div class="bill-item expense" v-if="localFormData.feeConfig.governmentSubsidy > 0">
                  <span class="item-name">政府补贴：</span>
                  <span class="item-amount">-{{ formatPrice(localFormData.feeConfig.governmentSubsidy) }}元</span>
                </div>
              </div>
              
              <div class="bill-total">
                <div class="monthly-total">
                  <strong>月费用总计：</strong>
                  <span class="total-amount">{{ formatPrice(monthlyTotal) }}元</span>
                </div>
                <div class="deposit-total" v-if="localFormData.feeConfig.deposit > 0">
                  <strong>押金：</strong>
                  <span class="deposit-amount">{{ formatPrice(localFormData.feeConfig.deposit) }}元</span>
                </div>
                <div class="final-total">
                  <strong>首期应付款：</strong>
                  <span class="final-amount">{{ formatPrice(firstPaymentTotal) }}元</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="dialog-actions">
          <button class="confirm-btn" @click="showBillPreviewDialog = false">确认</button>
        </div>
      </div>
    </div>

    <!-- 步骤导航 -->
    <div class="step-actions">
      <button @click="$emit('prev')">上一步</button>
      <button @click="completeStep" :disabled="!isStepValid">下一步</button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { listBed } from "@/api/le/bed"
import { updateElderly } from "@/api/le/elderly"
import { listFloorAllRelations } from "@/api/le/floor"
import { listLevel } from "@/api/level/level"
import { addBill } from "@/api/le/bill"
import { useUserStore } from '@/store/modules/user'

const props = defineProps({
  formData: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['next', 'prev', 'update:form-data'])

const stepTitle = '第四步：参数配置'

// 使用用户store
const userStore = useUserStore()

// 本地状态
const localFormData = reactive(JSON.parse(JSON.stringify(props.formData)))

// 床位选择相关状态
const showBedSelection = ref(false)
const showBillPreviewDialog = ref(false)
const bedSearchKey = ref('')
const bedFilterType = ref('')
const bedLoading = ref(false)

// 护理等级列表（从数据库获取）
const levelList = ref([])
const levelLoading = ref(false)

// 床位数据（从数据库获取）
const availableBeds = ref([])

// 监听父组件数据变化
watch(() => props.formData, (newData) => {
  Object.assign(localFormData, newData)
}, { deep: true })

// 计算属性
const filteredBeds = computed(() => {
  const filtered = availableBeds.value.filter(bed => {
    // 搜索条件：床位号、房间号、楼层名称
    const matchesSearch = !bedSearchKey.value || 
      bed.bedNo.includes(bedSearchKey.value) || 
      (bed.roomName && bed.roomName.includes(bedSearchKey.value)) ||
      (bed.floorName && bed.floorName.includes(bedSearchKey.value))
    
    // 床位类型筛选 - 根据显示的床位类型进行筛选
    const bedTypeLabel = getBedTypeLabel(bed.bedType)
    const matchesType = !bedFilterType.value || 
      bedTypeLabel === bedFilterType.value
    
    // 可用性筛选：status为0表示空闲，isDeleted为0表示未删除
    const isAvailable = bed.status === 0 || bed.status === '0'
    const isNotDeleted = bed.isDeleted === 0 || bed.isDeleted === '0'
    
    return matchesSearch && matchesType && isAvailable && isNotDeleted
  })
  
  return filtered
})

const monthlyTotal = computed(() => {
  const { careFee, bedFee, otherFee, medicalInsurance, governmentSubsidy } = localFormData.feeConfig
  return (Number(careFee) || 0) + (Number(bedFee) || 0) + (Number(otherFee) || 0) - (Number(medicalInsurance) || 0) - (Number(governmentSubsidy) || 0)
})

const calculateMonths = computed(() => {
  const { startDate, endDate } = localFormData.feeConfig
  if (!startDate || !endDate) return 0
  
  const start = new Date(startDate)
  const end = new Date(endDate)
  const months = (end.getFullYear() - start.getFullYear()) * 12 + (end.getMonth() - start.getMonth())
  return Math.max(months, 1)
})

const firstPaymentTotal = computed(() => {
  return monthlyTotal.value + (Number(localFormData.feeConfig.deposit) || 0)
})

// 验证逻辑
const isAdmissionConfigValid = computed(() => {
  const config = localFormData.admissionConfig
  return !!config.duration && !!config.levelId && !!config.selectedBed
})

const isFeeConfigValid = computed(() => {
  const fee = localFormData.feeConfig
  return !!fee.startDate && !!fee.endDate && fee.careFee !== '' && fee.bedFee !== ''
})

const isStepValid = computed(() => {
  return isAdmissionConfigValid.value && isFeeConfigValid.value
})

// 方法
const getBedTypeLabel = (type) => {
  // 如果输入为空或undefined，返回默认值
  if (!type || type === 'undefined') {
    return '未设置'
  }
  
  // 如果已经是汉字，直接返回
  if (['单人间', '两人间', '三人间', '四人间'].includes(type)) {
    return type
  }
  
  // 如果是数字，转换为汉字
  const typeMap = {
    '1': '单人间',
    '2': '两人间', 
    '3': '三人间',
    '4': '四人间',
    1: '单人间',
    2: '两人间', 
    3: '三人间',
    4: '四人间'
  }
  
  return typeMap[type] || type
}

// 获取床位类型对应的价格
const getBedTypePrice = (type) => {
  // 先转换为字符串进行处理
  const typeStr = String(type).trim()
  
  // 价格映射表
  const priceMap = {
    '单人间': 1600,
    '两人间': 1200,
    '三人间': 800,
    '四人间': 600,
    '1': 1600,
    '2': 1200,
    '3': 800,
    '4': 600
  }
  
  // 尝试直接匹配
  let price = priceMap[typeStr]
  
  // 如果没找到，尝试数字转换后匹配
  if (price === undefined) {
    const numType = parseInt(typeStr)
    if (!isNaN(numType)) {
      price = priceMap[String(numType)]
    }
  }
  
  // 如果还是没找到，尝试通过床位类型标签匹配
  if (price === undefined) {
    const bedTypeLabel = getBedTypeLabel(type)
    price = priceMap[bedTypeLabel]
  }
  
  return price || 0
}

// 格式化价格显示，保留两位小数
const formatPrice = (price) => {
  const numPrice = Number(price) || 0
  return numPrice.toFixed(2)
}

// 生成6位随机账单编号
const generateBillNo = () => {
  return Math.floor(100000 + Math.random() * 900000).toString()
}

// 获取当前月份（YYYY-MM格式）
const getCurrentMonth = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  return `${year}-${month}`
}

// 处理费用输入，限制为两位小数
const handleFeeInput = (value, fieldName) => {
  if (value === '' || value === null || value === undefined) {
    localFormData.feeConfig[fieldName] = ''
    return
  }
  
  // 转换为数字
  let numValue = Number(value)
  
  // 如果不是有效数字，设为0
  if (isNaN(numValue)) {
    numValue = 0
  }
  
  // 限制为两位小数
  numValue = Math.round(numValue * 100) / 100
  
  // 更新值
  localFormData.feeConfig[fieldName] = numValue
  
  // 重新计算总费用
  calculateTotalFee()
}

// 各个费用字段的输入处理函数
const handleDepositInput = (event) => {
  handleFeeInput(event.target.value, 'deposit')
}

const handleCareFeeInput = (event) => {
  handleFeeInput(event.target.value, 'careFee')
}

const handleBedFeeInput = (event) => {
  handleFeeInput(event.target.value, 'bedFee')
}

const handleOtherFeeInput = (event) => {
  handleFeeInput(event.target.value, 'otherFee')
}

const handleMedicalInsuranceInput = (event) => {
  handleFeeInput(event.target.value, 'medicalInsurance')
}

const handleGovernmentSubsidyInput = (event) => {
  handleFeeInput(event.target.value, 'governmentSubsidy')
}

// 处理护理等级变化
const handleLevelChange = (levelId) => {
  if (!levelId) {
    // 清空护理费用
    localFormData.feeConfig.careFee = ''
    calculateTotalFee()
    return
  }
  
  // 找到选中的护理等级
  const selectedLevel = levelList.value.find(level => level.id == levelId)
  if (selectedLevel && selectedLevel.nursingFee) {
    // 自动设置护理费用
    localFormData.feeConfig.careFee = selectedLevel.nursingFee
    calculateTotalFee()
    ElMessage.success(`已自动设置护理费用为 ${formatPrice(selectedLevel.nursingFee)} 元/月`)
  } else {
    ElMessage.warning('该护理等级未设置价格，请手动输入护理费用')
  }
}

const selectBed = (bed) => {
  // 根据床位类型获取标准价格
  const standardPrice = getBedTypePrice(bed.bedType)
  
  localFormData.admissionConfig.selectedBed = {
    id: bed.id,
    name: bed.bedNo,
    type: getBedTypeLabel(bed.bedType),
    price: standardPrice,
    room: bed.roomName || '',
    floor: bed.floorName || '',
    roomType: bed.roomType || '未设置'
  }
  // 自动设置床位费用为标准价格
  localFormData.feeConfig.bedFee = standardPrice
  calculateTotalFee()
}

const confirmBedSelection = () => {
  showBedSelection.value = false
  updateFormData()
}

const showBillPreview = () => {
  if (!isFeeConfigValid.value) {
    alert('请先完善费用设置信息')
    return
  }
  showBillPreviewDialog.value = true
}

const calculateTotalFee = () => {
  // 费用计算逻辑已经在计算属性中实现
  updateFormData()
}

// 加载护理等级数据
const loadLevelData = async () => {
  try {
    levelLoading.value = true
    
    const response = await listLevel({
      pageNum: 1,
      pageSize: 1000,
      status: 1 // 只获取启用状态的护理等级
    })
    
    if (response.code === 200 && Array.isArray(response.rows)) {
      levelList.value = response.rows.filter(level => level.status === 1) // 确保只显示启用状态的等级
    } else {
      console.error('护理等级API返回错误:', response)
      ElMessage.error('加载护理等级数据失败: ' + (response.msg || '未知错误'))
    }
  } catch (error) {
    console.error('加载护理等级数据失败:', error)
    ElMessage.error('加载护理等级数据失败: ' + error.message)
  } finally {
    levelLoading.value = false
  }
}

// 加载床位数据（使用联查方式获取楼层-房间-床位完整信息）
const loadBedData = async () => {
  try {
    bedLoading.value = true
    
    // 使用联查接口获取楼层及其关联的房间和床位数据
    const response = await listFloorAllRelations()
    
    if (response.code === 200 && Array.isArray(response.data)) {
      // 从所有楼层的房间中提取床位数据
      const allBeds = []
      
      response.data.forEach(floor => {
        if (floor.roomList && Array.isArray(floor.roomList)) {
          floor.roomList.forEach(room => {
            if (room.bedList && Array.isArray(room.bedList)) {
              room.bedList.forEach(bed => {
                // 根据房间类型推断床位类型
                let bedType = bed.bedType || bed.bed_type
                if (!bedType && room.roomType?.roomType) {
                  // 根据房间类型推断床位类型
                  const roomType = room.roomType.roomType
                  if (roomType.includes('单人间') || roomType.includes('单人')) {
                    bedType = '1'
                  } else if (roomType.includes('两人间') || roomType.includes('两人') || roomType.includes('双人')) {
                    bedType = '2'
                  } else if (roomType.includes('三人间') || roomType.includes('三人')) {
                    bedType = '3'
                  } else if (roomType.includes('四人间') || roomType.includes('四人')) {
                    bedType = '4'
                  }
                }
                
                // 为每个床位添加楼层和房间信息
                allBeds.push({
                  ...bed,
                  bedType: bedType, // 确保床位类型字段存在
                  floorId: floor.id,
                  floorName: floor.floorName,
                  roomId: room.id,
                  roomName: room.roomNo,
                  roomType: room.roomType?.roomType || '未设置'
                })
              })
            }
          })
        }
      })
      
      availableBeds.value = allBeds
    } else {
      console.error('联查API返回错误:', response)
      ElMessage.error('加载床位数据失败: ' + (response.msg || '未知错误'))
    }
  } catch (error) {
    console.error('加载床位数据失败:', error)
    ElMessage.error('加载床位数据失败: ' + error.message)
  } finally {
    bedLoading.value = false
  }
}

// 更新老人床位信息
const updateElderlyBed = async () => {
  try {
    if (!localFormData.elder?.id || !localFormData.admissionConfig.selectedBed?.id) {
      return
    }

    const updateData = {
      id: localFormData.elder.id,
      bedId: localFormData.admissionConfig.selectedBed.id
    }

    const response = await updateElderly(updateData)
    if (response.code === 200) {
      ElMessage.success('床位分配成功')
    } else {
      ElMessage.error('床位分配失败')
    }
  } catch (error) {
    console.error('更新老人床位失败:', error)
    ElMessage.error('床位分配失败')
  }
}

// 创建账单
const createBill = async () => {
  try {
    if (!localFormData.elder?.id) {
      throw new Error('老人信息不完整')
    }

    const billData = {
      billNo: generateBillNo(),
      billType: '入住账单',
      billMonth: getCurrentMonth(),
      elderlyId: localFormData.elder.id,
      monthlyPayable: monthlyTotal.value,
      currentPayable: firstPaymentTotal.value,
      prepaymentAmount: Number(localFormData.feeConfig.deposit) || 0,
      billAmount: monthlyTotal.value,
      payableAmount: firstPaymentTotal.value,
      paymentDeadline: localFormData.feeConfig.endDate,
      billStartTime: localFormData.feeConfig.startDate,
      billEndTime: localFormData.feeConfig.endDate,
      transactionStatus: '待支付',
      creator: userStore.id || 1,
      extraField1: JSON.stringify({
        levelId: localFormData.admissionConfig.levelId,
        bedId: localFormData.admissionConfig.selectedBed?.id,
        duration: localFormData.admissionConfig.duration
      })
    }

    const response = await addBill(billData)
    if (response.code === 200) {
      ElMessage.success('账单创建成功')
      return response.data
    } else {
      throw new Error(response.msg || '账单创建失败')
    }
  } catch (error) {
    console.error('创建账单失败:', error)
    ElMessage.error('账单创建失败: ' + error.message)
    throw error
  }
}

const completeStep = async () => {
  try {
    // 更新老人床位信息
    await updateElderlyBed()
    
    // 创建账单
    await createBill()
    
    // 更新表单数据
    updateFormData()
    
    // 进入下一步
    emit('next')
  } catch (error) {
    console.error('完成步骤失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 更新表单数据
const updateFormData = () => {
  emit('update:form-data', localFormData)
}

// 测试价格计算
const testPriceCalculation = () => {
  const testTypes = ['1', '2', '3', '4', '单人间', '两人间', '三人间', '四人间']
  testTypes.forEach(type => {
    const price = getBedTypePrice(type)
    const label = getBedTypeLabel(type)
  })
}

// 初始化
onMounted(() => {
  // 加载护理等级数据
  loadLevelData()
  
  // 加载床位数据
  loadBedData()
  
  // 测试价格计算
  setTimeout(() => {
    testPriceCalculation()
  }, 1000)
})
</script>

<style scoped>
.step-panel h2 {
  color: #1f2937;
  margin-top: 0;
  padding-bottom: 15px;
  border-bottom: 1px solid #e5e7eb;
}

/* 入住设置样式 */
.admission-config-section,
.fee-config-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: white;
}

.admission-config-section h3,
.fee-config-section h3 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #1f2937;
  border-bottom: 2px solid #3b82f6;
  padding-bottom: 10px;
}

/* 表单样式 */
.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #4b5563;
  font-weight: 500;
}

.required {
  color: #ef4444;
}

input,
select,
textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

/* 入住期限样式 */
.duration-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.duration-input {
  flex: 1;
}

.duration-unit {
  color: #6b7280;
  white-space: nowrap;
}

/* 床位选择样式 */
.bed-selection {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.bed-select-btn {
  padding: 10px 16px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  background: white;
  color: #374151;
  cursor: pointer;
  text-align: left;
  transition: all 0.3s ease;
}

.bed-select-btn:hover {
  border-color: #3b82f6;
  background: #f0f7ff;
}

.bed-info {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 8px 12px;
  background: #f8fafc;
  border-radius: 4px;
  border: 1px solid #e5e7eb;
}

.bed-name {
  font-weight: 600;
  color: #1e40af;
}

.bed-type {
  color: #6b7280;
  font-size: 14px;
}

.bed-price {
  color: #059669;
  font-weight: 500;
}

/* 费用提醒样式 */
.fee-notice {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px 16px;
  background: #dbeafe;
  border: 1px solid #93c5fd;
  border-radius: 6px;
  margin-bottom: 20px;
}

.notice-icon {
  font-size: 18px;
}

.notice-content {
  flex: 1;
  color: #1e40af;
  font-size: 14px;
}

/* 账单预览按钮样式 */
.bill-preview-section {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e5e7eb;
}

.bill-preview-btn {
  background: #3b82f6;
  color: white;
  padding: 10px 24px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.2s;
}

.bill-preview-btn:hover {
  background: #2563eb;
  transform: translateY(-1px);
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.bed-selection-dialog {
  background: white;
  border-radius: 8px;
  padding: 24px;
  width: 90%;
  max-width: 800px;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.bill-preview-dialog {
  background: white;
  border-radius: 8px;
  padding: 24px;
  width: 90%;
  max-width: 500px;
}

.dialog-content {
  margin-bottom: 20px;
  flex: 1;
  overflow-y: auto;
}

/* 床位筛选样式 */
.bed-filter {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e5e7eb;
}

/* 床位列表样式 */
.bed-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 12px;
  max-height: 400px;
  overflow-y: auto;
  flex: 1;
}

.bed-item {
  border: 2px solid #e5e7eb;
  border-radius: 6px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.2s;
  background: white;
}

.bed-item:hover {
  border-color: #93c5fd;
  background: #f0f7ff;
}

.bed-selected {
  border-color: #3b82f6;
  background: #eff6ff;
}

.bed-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.bed-name {
  font-weight: 600;
  color: #1f2937;
}

.bed-status {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
  font-weight: 500;
}

.status-available {
  background: #d1fae5;
  color: #065f46;
}

.status-occupied {
  background: #fef3c7;
  color: #d97706;
}

.bed-details {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
  font-size: 14px;
}

.bed-type {
  color: #6b7280;
}

.bed-price {
  color: #059669;
  font-weight: 500;
}

.bed-location {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 12px;
  color: #9ca3af;
}

.location-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.room-type-info {
  display: flex;
  justify-content: center;
}

.room-type {
  background-color: #f0f9ff;
  color: #1890ff;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 11px;
  border: 1px solid #d6f7ff;
}

.no-beds {
  text-align: center;
  color: #9ca3af;
  padding: 40px;
  grid-column: 1 / -1;
}

/* 账单预览样式 */
.bill-summary {
  padding: 16px;
  background: #f8fafc;
  border-radius: 6px;
}

.bill-period {
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e7eb;
  color: #374151;
}

.bill-details h4 {
  margin: 0 0 12px 0;
  color: #1f2937;
}

.bill-items {
  margin-bottom: 20px;
}

.bill-item {
  display: flex;
  justify-content: space-between;
  padding: 6px 0;
  border-bottom: 1px dashed #e5e7eb;
}

.bill-item.income .item-amount {
  color: #059669;
  font-weight: 500;
}

.bill-item.expense .item-amount {
  color: #dc2626;
  font-weight: 500;
}

.bill-total {
  padding-top: 12px;
  border-top: 2px solid #e5e7eb;
}

.monthly-total,
.deposit-total,
.final-total {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
}

.final-total {
  border-top: 1px solid #e5e7eb;
  margin-top: 8px;
  padding-top: 12px;
}

.total-amount,
.final-amount {
  color: #dc2626;
  font-weight: 600;
  font-size: 18px;
}

.deposit-amount {
  color: #d97706;
  font-weight: 500;
}

/* 对话框操作按钮 */
.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}

.cancel-btn {
  background: #f3f4f6;
  color: #374151;
  border: 1px solid #d1d5db;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-btn {
  background: #3b82f6;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

/* 按钮区域样式 */
.step-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 40px;
}

button {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  border: none;
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

button:not(:disabled):hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

button:nth-of-type(1) {
  background-color: #f3f4f6;
  color: #1f2937;
}

button:nth-of-type(2),
button:last-child {
  background-color: #3b82f6;
  color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .bed-list {
    grid-template-columns: 1fr;
  }
  
  .bed-filter {
    flex-direction: column;
  }
  
  .bill-preview-dialog {
    margin: 20px;
    width: calc(100% - 40px);
  }
  
  .duration-group {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .duration-unit {
    text-align: center;
  }
  
  .bed-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}
</style>
